const axios = require("axios")
const xlsx = require("node-xlsx")
const qs = require("qs")
const fs = require("fs")

// 读取Exel文件
async function readExel(fileName,color,lineWidth){
    // 获取Excel中所有表
    let sheets = xlsx.parse(`./execl/${fileName}`)
    let queryName = ""
    // 遍历sheet
    sheets.forEach((sheet) => {
        for(let rowId in sheet['data']){
            if(rowId !== 0){
                if(sheet["data"][rowId][4]){
                    let trembl = sheet["data"][rowId][4].split("|")[1]
                    queryName = `${queryName}\nUNIPROT:${trembl}`
                }else{
                    console.log(rowId+"为空")
                }
            }
        }
    })
    let svgFile = await drawing(queryName,fileName,color,lineWidth)
    await transferFile( svgFile , fileName)
}

// 发送作图请求

async function drawing(queryName,fileName,color,lineWidth){
    let svg = ""
    let selection = `${queryName} ${color} ${lineWidth}`
    let result = await axios({
        url:"https://pathways.embl.de/mapping.cgi",
        method:"POST",
        headers: { 'content-type': 'application/x-www-form-urlencoded' },
        data : qs.stringify({
            selection : selection,
            default_opacity: 1,
            default_width: 3,
            default_radius : 7,
            default_color : "#aaaaaa",
            background_color : "#ffffff",
            tax_filter : "",
            map : "metabolic",
            export_type : "svg",
            export_dpi : 120
        })
    })
    if(result.status === 200){
        svg = "<svg" + result.data.split("<svg")[1]
        console.log(`${fileName}.svg文件获取成功！`)
    }else{
        console.log("请求失败")
    }
    return svg
}

// 转存文件
async function transferFile(svg,fileName = "picture"){
    await fs.writeFile(`./svg/${fileName}.svg`,svg, err => {
        if(err){
            throw err
        }
        console.log(`${fileName}.svg文件写入完成！`)
    })
}

// 主程序
function main(){
    let color = "#ffffff"
    let lineWidth = "W20"
    let exelNames = fs.readdirSync("./execl/")
    exelNames.forEach((value,index,array) => {
        readExel(value,color,lineWidth)
        console.log(`${value}表转换完成`)
    })
    console.log("操作完成")
}

main()